package com.orange.delivery.presentation.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.ResourceModel;

import com.orange.delivery.presentation.WicketSession;

/**
 * Utility Model that formats dates to a string, using the pattern provided or the pattern available with the "dateTimePattern" key
 * Max date (01/01/2038) is converted to the string available with the "date.2038" key
 */
public class DateFormatModel extends AbstractReadOnlyModel<String> implements IModel<String> {
	private static final long serialVersionUID = -35404638368781239L;

	private final Date date;
	private final String dateTimePattern;

	public DateFormatModel(Date date, String dateTimePattern) {
		super();
		this.date = date;
		this.dateTimePattern = dateTimePattern;
	}

	public DateFormatModel(Date date) {
		super();
		this.date = date;
		ResourceModel resource = new ResourceModel("dateTimePattern");
		this.dateTimePattern = resource.getObject();
	}

	@Override
	public String getObject() {
		if (date == null) {
			return null;
		} else if (date.getTime() >= new GregorianCalendar(2038, 0, 1).getTime().getTime()) {
			// max date means no date
			return new ResourceModel("date.2038", "").getObject();
		} else {
			return getFormat().format(date);
		}
	}

	private DateFormat getFormat() {
		return new SimpleDateFormat(dateTimePattern, WicketSession.get().getLocale());
	}

}
